package cn.fl.infside.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.infside.service.IInfPostCollectMasterService;
import cn.fl.infside.transform.InfPostCollectMasterVOTransform;
import cn.fl.infside.vo.InfPostCollectMasterVO;
import cn.fl.system.constant.SysLogConstant;
import fl.inf.facade.condition.InfPostCollectMasterQueryCondition;
import fl.inf.facade.constant.InterfaceConstants;
import fl.inf.facade.dto.InfPostCollectMasterDTO;
import fl.inf.facade.dto.MessageDTO;

/**
 * @Description: 邮储代扣主表 控制层
 */
@Controller
@RequestMapping("/infside/infPostCollectMaster")
public class InfPostCollectMasterController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InfPostCollectMasterController.class);

	/**
	 * InfPostCollectMaster 服务层BEAN
	 */
	@Autowired
	private IInfPostCollectMasterService infPostCollectMasterService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toInfPostCollectManage.do", method = { RequestMethod.GET})
	public ModelAndView toInfPostCollectManage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("infside/infPostCollectMaster/infPostCollectManage");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toInfPostCollectMasterList.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("infside/infPostCollectMaster/infPostCollectMasterList");
		List<Map<String,String>> statuslist = new ArrayList<Map<String,String>>();
		for(InterfaceConstants.PostStatus status : InterfaceConstants.PostStatus.values()){
			Map<String,String> statusmap = new HashMap<String,String>();
			statusmap.put("key",status.key());
			statusmap.put("value",status.desc());
			statuslist.add(statusmap);
		}
		List<Map<String,String>> typelist = new ArrayList<Map<String,String>>();
		Map<String,String> typemap1 = new HashMap<String,String>();
		typemap1.put("key","0");
		typemap1.put("value","租金代扣");
		typelist.add(typemap1);
		Map<String,String> typemap2 = new HashMap<String,String>();
		typemap2.put("key","1");
		typemap2.put("value","验证代扣");
		typelist.add(typemap2);
		Map<String,String> typemap3 = new HashMap<String,String>();
		typemap3.put("key","2");
		typemap3.put("value","手动代扣");
		typelist.add(typemap3);
		view.addObject("typelist", typelist);
		view.addObject("statuslist", statuslist);
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到手动代扣页面
	 */
	@RequestMapping(value = "/toManualDetaiPage.do", method = { RequestMethod.GET})
	public ModelAndView toManualDetaiPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("infside/infPostCollectMaster/manualDetaiPage");
		BaseLogUtils.info(logger, "toManualDetaiPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("infside/infPostCollectMaster/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initInfPostCollectMasterList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String crtTm = request.getParameter("crtTm");
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");
		String status = request.getParameter("status");
		String type = request.getParameter("type");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		InfPostCollectMasterQueryCondition qc = new InfPostCollectMasterQueryCondition();
		if (StringUtils.isNotEmpty(crtTm)) {
			qc.setCreateDateStr(crtTm);
		}
		if (StringUtils.isNotEmpty(beginDate)) {
			qc.setBeginDate(DateUtils.formatStringToDate(beginDate, "yyyy-MM-dd"));
		}
		if (StringUtils.isNotEmpty(endDate)) {
			qc.setEndDate(DateUtils.formatStringToDate(endDate, "yyyy-MM-dd"));
		}
		if (StringUtils.isNotEmpty(status)) {
			qc.setStatus(status);
		}
		if (StringUtils.isNotEmpty(type)) {
			qc.setType(type);
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.infPostCollectMasterService.searchListPage(page);
		List<InfPostCollectMasterVO> list = InfPostCollectMasterVOTransform.toVOList((List<InfPostCollectMasterDTO>) pager.getResultList());
		for(InfPostCollectMasterVO _vo : list){
			if(null != _vo.getType()){
				Map<String,String> typemap = new HashMap<String,String>();
				typemap.put("0","租金代扣");
				typemap.put("1", "验证代扣");
				typemap.put("2","手动代扣");
				_vo.setTypeNm(typemap.get(_vo.getType()));
			}
			if(null != _vo.getTotalAt()){
				_vo.setTotalAtdou(DecimalUtils.convertFenToYuan(_vo.getTotalAt()));
			}
			if(null != _vo.getSuccessAt()){
				_vo.setSuccessAtdou(DecimalUtils.convertFenToYuan(_vo.getSuccessAt()));
			}
			if(null != _vo.getFailureAt()){
				_vo.setFailureAtdou(DecimalUtils.convertFenToYuan(_vo.getFailureAt()));
			}
			if(StringUtils.isNotEmpty(_vo.getStatus())){
				for(InterfaceConstants.PostStatus _enumstatus : InterfaceConstants.PostStatus.values()){
					if(StringUtils.isNotEmpty(_enumstatus.key()) && (_vo.getStatus()).equals(_enumstatus.key())){
						_vo.setStatusNm(_enumstatus.desc());
						break;
					}
				}
			}
		}
		ListPageVO<InfPostCollectMasterVO> listPage = new ListPageVO<InfPostCollectMasterVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.infPostCollectMasterService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			InfPostCollectMasterVO vo = this.infPostCollectMasterService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		InfPostCollectMasterVO entity = null;
		try {
			entity = new InfPostCollectMasterVO();
			//TODO ADD PARAM
			Long id = this.infPostCollectMasterService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		InfPostCollectMasterVO entity = null;
		try {
			entity = new InfPostCollectMasterVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.infPostCollectMasterService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 发送代扣
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	@RequestMapping(value = "/sendDeductions.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object sendDeductions(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "发送完成");
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "sendDeductions", "发送数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.parseArray(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}
		try {
			MessageDTO<String> messagedto = this.infPostCollectMasterService.sendDeductions(idsList);
			if(!messagedto.isSuccess()){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				//result.setInfo(messagedto.getMessage());
				result.setInfo("发送失败");
				BaseLogUtils.info(logger, "sendDeductions", "发送失败", CurrentThreadContext.getCurrentUserName());
			}
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("发送失败！");
			logger.error("发送失败！", ex);
		}
		return result;
	}

	/**
	 * 获取代扣回传
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	@RequestMapping(value = "/receiveDeductions.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object receiveDeductions(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作完成");
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "receiveDeductions", "操作数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.parseArray(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}
		try {
			MessageDTO<String> messagedto = this.infPostCollectMasterService.receiveDeductions(idsList);
			if(!messagedto.isSuccess()){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				//result.setInfo(messagedto.getMessage());
				result.setInfo("操作失败");
				BaseLogUtils.info(logger, "receiveDeductions", "操作失败", CurrentThreadContext.getCurrentUserName());
			}
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("操作失败！");
			logger.error("操作失败！", ex);
		}
		return result;
	}

	/**
	 * 删除数据
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	@RequestMapping(value = "/deleteMasterById.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object deleteMasterById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String masterId = request.getParameter("masterId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功");
		if(StringUtils.isEmpty(masterId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "deleteMasterById", "操作数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			MessageDTO<String> messagedto = this.infPostCollectMasterService.deleteMasterById(Long.valueOf(masterId));
			if(!messagedto.isSuccess()){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				//result.setInfo(messagedto.getMessage());
				result.setInfo("删除失败");
				BaseLogUtils.info(logger, "deleteMasterById", "删除失败", CurrentThreadContext.getCurrentUserName());
			}
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("删除失败！");
			logger.error("删除失败！", ex);
		}
		return result;
	}
	/**
	 * 下载文件
	 */
	@RequestMapping(value = "/downMasterFile.do", method = { RequestMethod.GET })
	@ResponseBody
	public void downMasterFile(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String filename = request.getParameter("filename");
		String filepath = request.getParameter("filepath");
		if(StringUtils.isEmpty(filename) || StringUtils.isEmpty(filepath)){
			BaseLogUtils.info(logger, "downMasterFile", "参数为空!", CurrentThreadContext.getCurrentUserName());
		}
		try {
			OutputStream os = response.getOutputStream();
			response.reset();
			filename=new String(filename.getBytes("UTF-8"),"ISO8859-1");
			response.setHeader("Content-disposition", "attachment; filename="+filename);// 设定输出文件头
			//  以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(filepath));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			toClient.write(buffer);
			toClient.close();
			fis.close();
		} catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
		}
	}
}

